#coding=utf-8
import datetime
import pymysql.cursors
from jqdatasdk import *
# 假日表，当月１号插入下月交易日数据
auth('13353991972', '991972')


conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='root', db='stock',charset="utf8", cursorclass=pymysql.cursors.DictCursor) 
#connect()方法用于创建与数据库的连接，里面可以指定参数，这一步只是连接到了数据库，操作数据库还需要下面的游标  
cur = conn.cursor()#通过获取到的conn数据库的cursor方法创建游标


qsrt="select * from market_day order by id desc limit 1;"
cur.execute(qsrt)
results = cur.fetchone()
# print(results)

# 第一次执行
if results==None:
    days=get_trade_days(start_date='2019-10-16', end_date='2019-12-31')
    for day in days:
        sqlstr = "insert into market_day (market_day) values('%s')" %(day)
        cur.execute(sqlstr)
        conn.commit()  #提交数据进数据库
    qsrt="select * from market_day order by id desc limit 1;"
    cur.execute(qsrt)
    results = cur.fetchone()

nowday=datetime.datetime.now()
while int(results['MARKET_DAY'].year)<=int(str(nowday.year)):
    if str(nowday.month)=='12':
        d1 = datetime.datetime.strptime(str(results['MARKET_DAY']), '%Y-%m-%d')
        d2 = datetime.datetime.strptime(str(nowday.year)+'-12-31', '%Y-%m-%d')
        delta = d1 - d2
        # print(delta.days)
        if delta.days<=0:
            years=int(results['MARKET_DAY'].year)+1
            print(years)
            # years=int(nowday.year)+1
            newdays=get_trade_days(start_date=str(years)+'-01-01', end_date=str(years)+'-12-31')
            # print(newdays)
            for d in newdays:
                nstr = "insert into market_day (market_day) values('%s')" %(d)
                cur.execute(nstr)
                conn.commit()  #提交数据进数据库

    qsrt="select * from market_day order by id desc limit 1;"
    cur.execute(qsrt)
    results = cur.fetchone()


cur.close()  
conn.close()  #关闭数据库连接